package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BusinessMap;
import com.sky.result.Location;
import com.sky.result.PageResult;
import com.sky.result.ShowLocation;
import com.sky.service.OrdersService;
import com.sky.service.ShoppingCartUserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.vo.OrderVO;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartUserMapper shoppingCartUserMapper;

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    ShoppingCartUserService shoppingCartUserService;

    @Autowired
    BusinessMap businessMap;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    private static final String SEND_MAP = "https://api.map.baidu.com/geocoding/v3/";
    private static final String CODE = "d1xGOhQuGwUpGllju3mdG3GGGxaaYktj";

    @Transactional
    @Override
    public Orders submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 如果没有地址就不能下单
        AddressBook addressBook = addressBookMapper.findById(ordersSubmitDTO.getAddressBookId());
        String userDistance = (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail());

        Integer distance = getDistance(userDistance);
        if (distance > 50000) {
            throw new OrderBusinessException("对不起,订单距离商家超过5公里,商家不能配送");
        }

        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 如果购物车没用东西我们也不让提交订单
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartUserMapper.findByUserId(userId);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        // 创建订单,先copy
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // ==========1.设置订单表============
        // 设置订单号 通过当前创建的时间来设置 也可以加一些其他的
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        // 设置订单的状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 设置当前订单的用户Id
        orders.setUserId(userId);
        // 设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 设置订单支付的状态
        orders.setPayStatus(Orders.UN_PAID);
        // 设置订单收货人的手机号
        orders.setPhone(addressBook.getPhone());
        // 拼接地址,如果传来的是null就给该成空
        orders.setAddress(userDistance);
        User user = userMapper.findById(userId);
        // 设置当前的操作的用户名
        orders.setUserName(user.getName());
        // 设置当前订单的收货人的名字
        orders.setConsignee(addressBook.getConsignee());
        ordersMapper.save(orders);
        // ===============2.在搞订单详情表===========
        // 订单详情是跟着购物车来的,所以我们需要先遍历我们的购物车
        shoppingCartList.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            // 这里会把购物车的id也传到订单详情中,我们需要手动改回null
            orderDetail.setId(null);
            // 设置orderId
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.save(orderDetail);
        });

        // 3.=========最后我们清空购物车======
        shoppingCartUserMapper.clean(userId);
        return orders;
    }

    /**
     * 判断地址是否小于5公里
     *
     * @return
     */
    private Integer getDistance(String userDistance) {

        try {
            // 获取openid需要通过key value形式的参数获取,我们封装到map集合中
            HashMap<String, String> openMap = new HashMap<>();
            openMap.put("address", "北京市海淀区上地十街10号");
            openMap.put("output", "json");
            openMap.put("ak", CODE);
            openMap.put("callback", "showLocation");
            // 通过java请求把请求的地址和参数传进去
            String jsonStr = HttpClientUtil.doGet(SEND_MAP, openMap);
            int indexOf = jsonStr.indexOf("{");
            String substring = jsonStr.substring(indexOf, jsonStr.length() - 1);
            // 把获取到的json格式的String转换成json对象,通过map集合
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(substring, Map.class);

            Map resultMap = (Map) map.get("result");
            Map showLocation = (Map) resultMap.get("location");
            System.out.println(showLocation);
            double adminLng = (double) showLocation.get("lng");
            double adminLat = (double) showLocation.get("lat");


            // ====在获取用户的经纬度
            openMap.put("address", userDistance);
            // 通过java请求把请求的地址和参数传进去
            String jsonStr2 = HttpClientUtil.doGet(SEND_MAP, openMap);
            int indexOf2 = jsonStr2.indexOf("{");
            String substring2 = jsonStr2.substring(indexOf2, jsonStr2.length() - 1);
            // 把获取到的json格式的String转换成json对象,通过map集合
            Map map2 = objectMapper.readValue(substring2, Map.class);

            Map resultMap2 = (Map) map2.get("result");
            Map showLocation2 = (Map) resultMap2.get("location");
            double userLng = (double) showLocation2.get("lng");
            double userLat = (double) showLocation2.get("lat");

            String urlString = "https://api.map.baidu.com/directionlite/v1/driving?origin=" + adminLat + "," + adminLng + "&destination=" + userLat + "," + userLng + "&ak=" + CODE;
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 解析JSON字符串
                ObjectMapper objectMapper8 = new ObjectMapper();
                JsonNode rootNode = objectMapper8.readTree(response.toString());
                // 提取距离信息
                JsonNode resultNode = rootNode.get("result");
                if (resultNode != null) {
                    JsonNode routesNode = resultNode.get("routes");
                    if (routesNode != null && routesNode.isArray() && routesNode.size() > 0) {
                        JsonNode distanceNode = routesNode.get(0).get("distance");
                        if (distanceNode != null) {
                            double distance = distanceNode.asDouble();
                            System.out.println("Distance: " + distance);
                        }
                    }
                }

                ObjectMapper objectMapper1 = new ObjectMapper();
                Map readValue = objectMapper1.readValue(response.toString(), Map.class);
                Map resultLocation = (Map) readValue.get("result");
                ArrayList routes = (ArrayList) resultLocation.get("routes");
                Map mapcd = (Map) routes.get(0);
                Integer CD = (Integer) mapcd.get("distance");
                return CD;
            } else {
                System.out.println("GET request failed. Response Code: " + responseCode);
            }
            return null;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }


    @Override
    public void paymentSucceed(OrdersPaymentDTO ordersPaymentDTO) {
        // 这里可以通过微信获取的openId和前端传过来的订单
        // 我感觉也可以通过前端把当前操作的用户id传过来
        Orders orders = ordersMapper.findOrderByNum(ordersPaymentDTO.getOrderNumber());
        Orders bulidOrders = Orders.builder().id(orders.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .checkoutTime(LocalDateTime.now())
                .payStatus(Orders.PAID).build();
        ordersMapper.updateById(bulidOrders);
    }

    @Override
    public PageResult page(OrdersPageQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        Page<Orders> list = ordersMapper.page(queryDTO);
        long total = list.getTotal();
        List<Orders> result = list.getResult();
        Long userId = BaseContext.getCurrentId();
//        把list换成Orders中的list
        List<OrderVO> orderVOS = result.stream().map(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            List<OrderDetail> ord = orderDetailMapper.findByOrderId(orders.getId());
            orderVO.setOrderDetailList(ord);
            return orderVO;
        }).collect(Collectors.toList());
        return new PageResult(total, orderVOS);
    }


    /**
     * 接收前端传来的支付请求,后端去请求wx生成预支付交易单id,然后返回给前端
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.findById(userId);
        Orders orders = ordersMapper.findOrderByUserIdAndNum(userId, ordersPaymentDTO.getOrderNumber());
        // 调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = null;
        try {
            jsonObject = weChatPayUtil.pay(
                    ordersPaymentDTO.getOrderNumber(), // 商户订单号
                    new BigDecimal(orders.getPackAmount()), // 支付金额，单位 元
                    "描述", // 商品描述
                    user.getOpenid() // 微信用户的openid
            );
        } catch (Exception e) {
            throw new RuntimeException("支付失败");
        }

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }

    /**
     * 用户支付成功后,修改状态为已支付
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        Orders orders = ordersMapper.findOrderByNum(outTradeNo);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCheckoutTime(LocalDateTime.now());
        ordersMapper.updateById(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */

    @Override
    public void delivery(Long id) {
        Orders orders = ordersMapper.findById(id);
        // 如果没有订单不派送
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 如果没支付不派送
        if (orders.getPayStatus() != 1) {
            throw new OrderBusinessException("用户未支付,无法派送");
        }

        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.updateById(orders);
    }

    /**
     * 根据id取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrders(Long id) {
        // 构造Orders对象
        Orders orders = new Orders();
        // 构造id
        orders.setId(id);
        // 构造取消时间
        orders.setCancelTime(LocalDateTime.now());
        // 修改订单状态
        orders.setStatus(Orders.CANCELLED);
        ordersMapper.cancelOrders(orders);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrdersDetailVO findOrderDetailById(Long id) {
        // 根据id查询订单详情
        Orders orders = ordersMapper.findOrderById(id);
        // 根据id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.findOrderDetailByorderId(id);
        // 构造返回数据
        OrdersDetailVO ordersDetailVO = new OrdersDetailVO();
        BeanUtils.copyProperties(orders, ordersDetailVO);
        ordersDetailVO.setOrderDetailList(orderDetailList);
        return ordersDetailVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void again(Long id) {
        List<OrderDetail> orderDetailList = orderDetailMapper.findOrderDetailByorderId(id);
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCartDTO shoppingCartDTO = ShoppingCartDTO.builder()
                    .setmealId(orderDetail.getSetmealId())
                    .dishId(orderDetail.getDishId())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .build();
            shoppingCartUserService.addShoppingCart(shoppingCartDTO);
        }
    }

    /**
     * 根据id完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders order = ordersMapper.findById(id);
        // 设置状态
        order.setStatus(Orders.COMPLETED);
        // 设置送达时间
        order.setDeliveryTime(LocalDateTime.now());
        // 更新订单数据
        ordersMapper.updateById(order);
    }

    /**
     * 查看订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO findById(Long id) {
        Orders order = ordersMapper.findById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        // 获得订单菜品
        List<OrderDetail> list = orderDetailMapper.findByOrderId(id);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }


    /**
     * 商家接单
     *
     * @param id
     */
    @Override
    public void updateConfirm(Long id) {
//        根据id查询订单
        Orders orders = ordersMapper.findOrderById(id);
        orders.setStatus(Orders.CONFIRMED);
//        把数据库订单状态改成已接单
        ordersMapper.updateByIdOrders(orders);
    }

    /**
     * 商家拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void updateRejection(OrdersRejectionDTO ordersRejectionDTO) {
//        根据id查询订单
        Orders orders = ordersMapper.findOrderById(ordersRejectionDTO.getId());
//        填写拒单原因
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
//        修改订单状态和付款状态,取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelTime(LocalDateTime.now());
//        修改订单
        ordersMapper.updateById(orders);
    }
}
